import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'date_time_picker.dart';

class AddFoodRecordDialog extends StatefulWidget {
  final String babyId;
  const AddFoodRecordDialog({Key? key, required this.babyId}) : super(key: key);

  @override
  State<AddFoodRecordDialog> createState() => _AddFoodRecordDialogState();
}

class _AddFoodRecordDialogState extends State<AddFoodRecordDialog> {
  final _formKey = GlobalKey<FormState>();
  DateTime _date = DateTime.now();
  final _foodController = TextEditingController();
  final _amountController = TextEditingController();
  final _noteController = TextEditingController();
  String _reaction = '良好';

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加辅食记录'),
      content: Form(
        key: _formKey,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildDateTimePicker(),
            TextFormField(
              controller: _foodController,
              decoration: const InputDecoration(labelText: '食物名称'),
              validator: (value) => value?.isEmpty ?? true ? '请输入食物名称' : null,
            ),
            TextFormField(
              controller: _amountController,
              decoration: const InputDecoration(labelText: '食用量 (克)'),
              keyboardType: TextInputType.number,
            ),
            DropdownButtonFormField<String>(
              value: _reaction,
              decoration: const InputDecoration(labelText: '反应'),
              items:
                  ['良好', '一般', '排斥', '过敏']
                      .map((e) => DropdownMenuItem(value: e, child: Text(e)))
                      .toList(),
              onChanged: (value) {
                if (value != null) setState(() => _reaction = value);
              },
            ),
            TextFormField(
              controller: _noteController,
              decoration: const InputDecoration(labelText: '备注'),
              maxLines: 2,
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(onPressed: _submit, child: const Text('保存')),
      ],
    );
  }

  Widget _buildDateTimePicker() {
    return DateTimeFormField(
      label: '用餐时间',
      value: _date,
      onChanged: (value) => setState(() => _date = value),
      validator: (value) => value == null ? '请选择时间' : null,
      firstDate: DateTime.now().subtract(const Duration(days: 7)),
      lastDate: DateTime.now(),
    );
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.food,
          timestamp: _date,
          data: {
            'food': _foodController.text,
            'amount': _amountController.text,
            'reaction': _reaction,
            'note': _noteController.text,
          },
        ),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    }
  }

  @override
  void dispose() {
    _foodController.dispose();
    _amountController.dispose();
    _noteController.dispose();
    super.dispose();
  }
}
